package com.zhongxi.guoyuan.view.beautifulStore;

import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.Gson;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.beautifulOrder.BeautifulStoreOrderData;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.GlideRoundTransform;
import com.zhongxi.guoyuan.utils.MyTextUtils;
import com.zhongxi.guoyuan.view.MainHomeActivity;

import java.util.HashMap;
import java.util.Map;

public class BeautifulCommentActivity extends BaseActivity implements View.OnClickListener, TextWatcher {

    private BeautifulStoreOrderData list;
    private ImageView ivImg;
    private TextView tvName;
    private Button btSubscribe;
    private RatingBar rb;
    private TextView tvScore;
    private Map<String, String> map = new HashMap<>();
    private String star = "5";
    private EditText etTips;
    private TextView tvNum;
    private TextView tvTime;
    private TextView tvType;
    private TextView tvOrderId;
    private ImageView ivGif;

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_beautiful_comment);
        initTitle();
        tvTitle.setText("评价页面");
        Intent intent = getIntent();
        list = (BeautifulStoreOrderData)intent.getSerializableExtra("info");
        ivImg = (ImageView) findViewById(R.id.ivImg);
        tvName = (TextView) findViewById(R.id.tvName);
        tvTime = (TextView) findViewById(R.id.tvTime);
        tvType = (TextView) findViewById(R.id.tvType);
        tvOrderId = (TextView) findViewById(R.id.tvOrderId);
        tvScore = (TextView) findViewById(R.id.tvScore);
        tvNum = (TextView) findViewById(R.id.tvNum);
        etTips = (EditText) findViewById(R.id.etTips);
        btSubscribe = (Button) findViewById(R.id.btSubscribe);
        rb = (RatingBar) findViewById(R.id.rb);
        setData();
    }

    /**
     * 初始化数据
     */
    private void setData() {
        if(null!=list.getServiceimg()&&!"".equals(list.getServiceimg())){
            Glide.with(context).load(Url.IMG_URL+list.getServiceimg()).placeholder(R.mipmap.iv_eg).transform(new GlideRoundTransform(context, 20)).into(ivImg);
        }
        if(null!=list.getServicename()&&!"".equals(list.getServicename())){
            tvName.setText(list.getServicename());
        }else{
            tvName.setText("");
        }
        if(null!=list.getCtime()&&!"".equals(list.getCtime())){
            tvTime.setText("服务完成时间："+list.getCtime());
        }else{
            tvTime.setText("服务完成时间：******");
        }
        if(null!=list.getSstype()&&!"".equals(list.getSstype())){
            if("2".equals(list.getSstype())){
                tvType.setText("服务方式：到店服务");
            }else if("1".equals(list.getSstype())){
                tvType.setText("服务方式：上门服务");
            }
        }else{
            tvType.setText("服务方式：");
        }
        if(null!=list.getId()&&!"".equals(list.getId())){
            tvOrderId.setText("订单号："+list.getId());
        }else{
            tvOrderId.setText("订单号：***");
        }
    }

    @Override
    protected void initData() {
        super.initData();
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ivBack.setOnClickListener(this);
        btSubscribe.setOnClickListener(this);
        etTips.addTextChangedListener(this);
        rb.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener()
        {
            public void onRatingChanged(RatingBar ratingBar, float rating,  boolean fromUser) {
                star = rating+"";
                tvScore.setText(rating+"");
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ivBack:
                finish();
                break;
            case R.id.btSubscribe:
                if(!MyTextUtils.isFastDoubleClick()){
                    String content = etTips.getText().toString().trim();
                    if(TextUtils.isEmpty(content)){
                        showShortToast("评论内容不能为空！");
                    }else{
                        toComment(content);
                    }
                }
                break;
        }
    }

    /**
     * 评论
     * @param content
     */
    private void toComment(String content) {
        map.clear();
        map.put("orderid", list.getId());
        map.put("sid", list.getSid());
        map.put("starlevel", star);
        map.put("msg", content);
        getServer(Url.INNER_COMMENT, map, "", false, null, "post");
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        BaseResponse result = gson.fromJson(response, BaseResponse.class);
        MyApplication.getInstance().setSpValue(result.getSafeobj());
        showShortToast("评论成功");
        if(MyApplication.getInstance().isPrivilege()){
            showPopupWindow();
        }else{
            showPopWindow();
        }
    }

    private void showPopWindow() {
        try {
            LayoutInflater inflater = LayoutInflater.from(this);
            LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_comment_inner, null);
            final AlertDialog dialog = new AlertDialog.Builder(context).create();
            dialog.setCanceledOnTouchOutside(false);
            dialog.show();
            dialog.getWindow().setContentView(layout);
            TextView tvSurePay = (TextView) layout.findViewById(R.id.tvSure);
            ImageView ivCancel = (ImageView) layout.findViewById(R.id.ivCancel);
            ivCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    startAct(MainHomeActivity.class);
                    finish();
                }
            });
            tvSurePay.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    startAct(MainHomeActivity.class);
                    finish();
                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void showPopupWindow() {
        try {
            LayoutInflater inflater = LayoutInflater.from(this);
            LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_comment_success, null);
            final AlertDialog dialog = new AlertDialog.Builder(context).create();
            dialog.setCanceledOnTouchOutside(false);
            dialog.show();
            dialog.getWindow().setContentView(layout);
            TextView tvSurePay = (TextView) layout.findViewById(R.id.tvSure);
            TextView tvContent = (TextView) layout.findViewById(R.id.tvContent);
            ImageView ivCancel = (ImageView) layout.findViewById(R.id.ivCancel);
            ivGif = (ImageView) layout.findViewById(R.id.ivGif);
            Glide.with(context).load(R.mipmap.coin_drop).asGif().diskCacheStrategy(DiskCacheStrategy.SOURCE).into(ivGif);
            ivCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    startAct(MainHomeActivity.class);
                    finish();
                }
            });
            tvSurePay.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    startAct(MainHomeActivity.class);
                    finish();
                }
            });
            tvContent.setText((int) Float.parseFloat(list.getPay())+"银币");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        BaseResponse result = gson.fromJson(response, BaseResponse.class);
        if(null!=result.getSafeobj()&&!"".equals(result.getSafeobj()))
            MyApplication.getInstance().setSpValue(result.getSafeobj());
        if(1020==result.getCode()){
            showShortToast("评论服务暂不可用");
        }else{
            showShortToast("评论失败");
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable content) {
        MyTextUtils.TextChangeUtils(context, tvNum, content);
    }
}
